import os
from fastapi import FastAPI
from dotenv import load_dotenv
from tortoise.contrib.fastapi import register_tortoise
from api.application.apps.common.views import app as common_app
from api.application import settings
from api.application.utils import middleware, exception


def create_app() -> FastAPI:
    """工厂函数: 创建app对象"""

    # 加载env配置，加载到环境变量
    load_dotenv()

    app = FastAPI(
        title=os.environ.get('APP_NAME'),
        summary=os.environ.get('APP_SUMMARY'),
        description=os.environ.get('APP_DESCRIPTION'),
        version=os.environ.get('APP_VERSION'),
        # 注册全局异常
        exception_handlers={
            exception.HTTPException: exception.global_http_exception_handler,
            exception.RequestValidationError: exception.global_request_exception_handler
        }
    )

    # 把Tortoise-orm注册到App应用对象中
    register_tortoise(
        app,
        config=settings.TORTOISE_ORM,
        generate_schemas=False,  # 是否自动生成表结构 [api/application/settings/TORTOISE_ORM/apps的路径自动识别模型]
        add_exception_handlers=True,  # 是否启用自动异常处理
    )

    # 注册添加分路由
    app.include_router(common_app, prefix='/common')  # prefix 路径前缀

    # 注册中间件函数
    http_middleware = app.middleware('http')
    http_middleware(middleware.log_request)

    return app
